<template>
  <scroll-view class="flex-col page mine" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav :scrollTop="scrollTop" title="赛事详情" />
      <scroll-view scroll-y class="scroll-view-content">
        <!-- Athlete Info Bar -->
        <!-- <view class="athlete-bar">
          <text class="athleteNameStyle">

            当前运动员：
            <text class="athleteNameStyleValue">
              {{ athleteName }}
            </text>
          </text>
          <view class="switch-btn">
            <text>切换</text>
            <image class="switch-icon" :src="imgUrl + 'switch@2x.png'" mode="aspectFit" />
          </view>
        </view> -->

        <!-- Event Card -->
        <view class="event-card">
          <view class="event-image-wrapper">
            <image class="event-image" :src="eventDetail.base.master_image" mode="aspectFill" />
            <view class="event-status">
              <image class="status-icon" :src="imgUrl + '13362@2x.png'" mode="widthFix" />
              <text>{{ getEventStatusText(eventDetail.base.status) }}</text>
            </view>
          </view>
          <view class="event-info-main">
            <view class="event-title">{{ eventDetail.base.name }}</view>
            <!-- <view class="event-club">俱乐部：{{ eventDetail.base.club_name }}</view> -->
          </view>
        </view>
        <!-- Tabs -->
        <view class="tabs">
          <text v-for="(tab, index) in tabs" :key="index" :class="{ active: activeTab === index }" class="tab"
            @click="activeTab = index">
            {{ tab }}
          </text>
        </view>
        <!-- Tab Content -->
        <view class="tab-content">
          <!-- 详情 Tab -->
          <view v-if="activeTab === 0" class="details-section">
            <view class="info-list">
              <view class="info-item">
                <view class="label">俱乐部：</view>
                <view class="value">{{eventDetail.base.club_name }}</view>
              </view>
              <view class="info-item">
                <view class="label">比赛时间：</view>
                <view class="value">{{ formatTime(eventDetail.base.competition_time) }}</view>
              </view>
              <view class="info-item">
                <view class="label">截止时间：</view>
                <view class="value">{{ formatTime(eventDetail.base.deadline) }}</view>
              </view>
              <view class="info-item location">
                <view class="label">比赛地址：</view>
                <view class="display-flex">
                  <view class="value mr-auto">{{ eventDetail.base.address }}</view>
                  <view class="distance">
                    <image class="icon" :src="imgUrl + 'location.png'" mode="widthFix" />
                    {{
                      eventDetail.base.juli ? (eventDetail.base.juli / 1000).toFixed(2) : '0.00'
                    }}km
                  </view>
                </view>
              </view>
              <!-- <view class="info-item items">
                <text class="label">比赛项目：</text>
                <view class="tags">
                  <text class="tag" v-for="(item, index) in eventDetail.base.items" :key="index">{{
                    item.name
                  }}</text>
                </view>
              </view> -->
            </view>
            <view class="description-section">
              <rich-text :nodes="eventDetail.base.content"></rich-text>
              <image v-for="(img, index) in descImages" :key="index" :src="img" class="desc-img descriptive-image"
                mode="aspectFill" />
              <!-- <text>
                在短跑项目中，运动员们如同离弦之箭，从起跑线瞬间爆发，全力冲刺。百米赛跑更是被誉为“飞人之战”。短短十几秒内，选手们要将身体的潜能发挥到极致，每一次的0.01秒提升都凝聚着无数汗水与努力。跨栏比赛则更具观赏性，运动员们在跨越一道道框架的同时，还要保持高速奔跑，身体的协调性、节奏感和爆发力缺一不可。他们如同跨越障碍的勇士，在跑道上书写着速度与激情的传奇。
              </text> -->
            </view>
            <view class="accordion-section">
              <uv-collapse accordion>
                <uv-collapse-item title="赛事流程" name="process">
                  <view class="collapse-content">
                    <rich-text :nodes="eventDetail.base.process"></rich-text>
                  </view>
                </uv-collapse-item>
                <uv-collapse-item title="比赛规则" name="rules">
                  <view class="collapse-content">
                    <rich-text :nodes="eventDetail.base.rule"></rich-text>
                  </view>
                </uv-collapse-item>
                <uv-collapse-item title="比赛奖励" name="rewards">
                  <view class="collapse-content">
                    <rich-text :nodes="eventDetail.base.reward"></rich-text>
                  </view>
                </uv-collapse-item>
                <uv-collapse-item title="退费说明" name="refund">
                  <view class="collapse-content">
                    <rich-text :nodes="eventDetail.base.describe"></rich-text>
                  </view>
                </uv-collapse-item>
              </uv-collapse>
            </view>
            <!-- <view class="fab-container">
              <image :src="imgUrl + 'customerService2.png'" class="fab-icon" />
            </view> -->
          </view>

          <!-- 组别信息 Tab
          <view v-if="activeTab === 1" class="info-list">
            <GroupItem :categories="categories" v-if="categories.length > 0" />
          </view> -->

          <!-- 俱乐部 Tab
          <view v-if="activeTab === 2" class="info-list">
            <ClubList :clubs="clubData" v-if="clubData.length > 0" />
          </view> -->

          <!-- 赛程 Tab
          <view v-if="activeTab === 3" class="info-list">
            <ScheduleList :mainId="mainId" />
          </view>

          成绩 Tab
          <view v-if="activeTab === 4" class="info-list">
            <ResultList :mainId="mainId" :competition_time="competition_time" />
          </view> -->

          <!-- 赛程 Tab -->
          <view v-if="activeTab === 1" class="info-list">
            <ScheduleList :mainId="mainId" />
          </view>

          <!-- 成绩 Tab -->
          <view v-if="activeTab === 2" class="info-list">
            <ResultList :mainId="mainId" :competition_time="competition_time" />
          </view>
          <view v-if="activeTab === 3" class="info-list">
            <ClubList :clubs="clubData" v-if="clubData.length > 0" />
          </view> 
        </view>
      </scroll-view>
      <view class="footer-bar">
        <view class="footer-home" @click="goHome">
          <image :src="imgUrl + 'home@2x.png'" class="home-icon" />
          <text class="home-text">首页</text>
          <!-- <image :src="imgUrl + 'share@2x.png'" class="home-icon" />
          <text class="home-text">分享</text> -->
        </view>
        <view class="footer-home" @click="onShare">
          <!-- <image :src="imgUrl + 'home@2x.png'" class="home-icon" />
          <text class="home-text">首页</text> -->
          <image :src="imgUrl + 'share2@2x.png'" class="home-icon" />
          <text class="home-text">分享</text>
        </view>
        <button 
          :class="['save-btn', { 'disabled': !canRegister }]" 
          :disabled="!canRegister"
          @click="submitForm"
        > 
          {{ canRegister ? '我要报名' : '报名已截止' }}
        </button>
      </view>
    </view>
    <!-- <movable-area class="movable-area" @click="getNewsCustomer">
      <movable-view class="fab-container" direction="all" :x="x" :y="y">
        <image :src="imgUrl + 'customerService2.png'" class="fab-icon" />
      </movable-view>
    </movable-area> -->
  </scroll-view>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue'
import { useOutsideAppStore } from '@/store/app'
import { imgUrl } from '@/utils/config'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useRequest } from '@/api'
import GroupItem from '@/components/GroupItem/index.vue'
import ClubList from '@/components/ClubList/index.vue'
import ScheduleList from '@/components/ScheduleList/index.vue'
import ResultList from '@/components/ResultList/index.vue'
import { getEventStatusText, getEventTypeText } from '@/utils/statusUtils.js'
import { formatTime } from '@/utils/dateUtils.js'
const appStore = useOutsideAppStore()
const navHeight = computed(() => appStore.navHeight)
const scrollTop = ref(0)
const onPageScroll = (e) => {
  scrollTop.value = e.detail.scrollTop
}
const competition_time = ref('')
const userInfo = ref({})
const pageType = ref({})
const getNewsCustomer = async () => {
  console.log('getNewsCustomer+++++')
  try {
    const res = await API_NEWS_CUSTOMER_GET()
    console.log('getNewsCustomer————————————', res)

    if (res.code === 1) {
      // newsDetail.value = res.data;
      // // 拨打电话
      // uni.makePhoneCall({
      //   phoneNumber: '4000692928'
      // });
      // 拨打电话
      uni.makePhoneCall({
        phoneNumber: res.data.customer
      })
    } else {
      uni.showToast({ title: res.msg, icon: 'none' })
    }
  } catch (error) {
    console.log('error>>>>>>>+++++', error)
    uni.showToast({ title: error.response?.data.msg, icon: 'none' })
  }
}
const emit = defineEmits(['support', 'share'])
const { API_INDEX_DETAIL_POST, API_NEWS_CUSTOMER_GET } = useRequest()
const eventDetail = ref({
  base: {
    master_image: ''
  },
  group: [],
  club: [],
  course: [],
  score: []
})
const mainId = ref(0)
// 处理desc_image，将字符串转换为数组
const descImages = computed(() => {
  if (!eventDetail.value.base.desc_image) return []
  return eventDetail.value.base.desc_image.split(',').filter((img) => img.trim())
})
const x = ref(300)
const y = ref(500)
onMounted(() => {
  const { windowWidth, windowHeight } = uni.getSystemInfoSync()
  x.value = windowWidth - 60 // 50px width + 10px margin
  y.value = windowHeight - 150 // Adjust based on bottom bar height and safe area
})
const goHome = () => {
  uni.navigateTo({
    url: '/pages/leagueMatchesHome/index'
  })
}
const onShare = () => {
  emit('share', eventDetail.value)
}
onShow(() => {
  const pages = getCurrentPages() // 获取当前页面栈
  const currentPage = pages[pages.length - 1] // 获取当前页面
  console.log('currentPage', currentPage)

  const options = currentPage.options // 获取当前页面的参数
  const { id } = options
  if (id) {
    getEventDetail(id)
  }
})
const getEventDetail = async (id) => {
  const longitude = uni.getStorageSync('longitude')
  const latitude = uni.getStorageSync('latitude')
  let params = {
    id: id,
    lng: longitude,
    lat: latitude
  }
  eventDetail.value = {
    base: {
      master_image: ''
    },
    group: [],
    club: [],
    course: [],
    score: []
  }
  categories.value = []
  clubData.value = []
  scheduleData.value = []
  resultData.value = []
  mainId.value = id
  try {
    const res = await API_INDEX_DETAIL_POST(params)
    console.log('getEventDetail', res)

    if (res.code === 1) {
      eventDetail.value = res.data
      // mainId.value = res.data.base.id
      console.log('eventDetail', eventDetail.value)
      categories.value = res.data.group //组别
      console.log('categories', categories.value)
      clubData.value = res.data.club //俱乐部
      console.log('mainId', mainId.value)
      competition_time.value = res.data.base.competition_time
      // console.log('clubData', clubData.value)
      // scheduleData.value = res.data.course;//赛程
      // console.log('scheduleData', scheduleData.value)
      // resultData.value = res.data.score;//成绩
      // console.log('resultData', resultData.value)
    } else {
      uni.showToast({ title: res.msg, icon: 'none' })
    }
  } catch (error) {
    uni.showToast({ title: error.message, icon: 'none' })
  }
}
const categories = ref([
  {
    type: '100M',
    items: [
      {
        color: '#1D428A',
        name: '公开男子',
        restriction: '不限年龄'
      },
      {
        color: '#C8102E',
        name: '公开女子',
        restriction: '不限年龄'
      },
      {
        color: '#D87E04',
        name: 'U4混合',
        restriction: '2009.01.12后出生者'
      }
    ]
  },
  {
    type: '60M',
    items: [
      {
        name: '公开男2子',
        restriction: '不限年龄'
      }
    ]
  }
])
const clubData = ref([
  { logo: imgUrl + 'firstPlace.png', name: '新博体育', score: '4000' },
  { logo: imgUrl + 'firstPlace.png', name: '心悸体育', score: '3500' },
  { logo: imgUrl + 'firstPlace.png', name: '内蒙古图腾俱乐部', score: '2000' },
  { logo: imgUrl + 'firstPlace.png', name: '田径运动协会', score: '666' },
  { logo: imgUrl + 'firstPlace.png', name: '包头市第四十八中学', score: '223' }
])
const scheduleData = ref([
  { date: '2024.12.12', time: '09:00:00', group: '1500M' },
  { date: '2024.12.12', time: '09:00:00', group: '1500M' },
  { date: '2024.12.12', time: '09:00:00', group: '1500M' },
  { date: '2024.12.12', time: '09:00:00', group: '1500M' },
  { date: '2024.12.12', time: '09:00:00', group: '1500M' },
  { date: '2024.12.12', time: '09:00:00', group: '1500M' }
])
const resultData = ref([
  {
    name: '吴涛',
    number: '1290',
    avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
    time: '09:00',
    result: '冠军'
  },
  {
    name: '吴涛',
    number: '1290',
    avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
    time: '09:00',
    result: '冠军'
  }
])

const submitForm = () => {
  // 检查赛事是否已结束
  if (!canRegister.value) {
    uni.showToast({
      title: '报名已截止',
      icon: 'none'
    })
    return
  }

  // 表单提交校验
  // 这里可以根据实际需求实现表单验证逻辑
  console.log('submitForm', 'mainId', mainId.value)

  let info = uni.getStorageSync('userInfo') || null
  if (typeof info === 'string') {
    try {
      info = JSON.parse(info)
    } catch { }
  }
  userInfo.value = info
  //检测是否登录
  checkLogin()
}
const checkLogin = () => {
  console.log('checkLogin>>>', userInfo.value)
  if (!userInfo.value || !userInfo.value.mobile) {
    //未登录
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/index'
      })
    }, 1500)
    return
  } else {
    uni.navigateTo({
      url: '/pages/registration/index?event_id=' + mainId.value
    })
  }
}
const athleteName = ref('李思雨')

const event = ref({
  img: 'https://cdn.uviewui.com/uview/swiper/1.jpg',
  status: '报名中',
  title: '草源体育公开赛田径运动 · 郑州站',
  club: '草源体育'
})

//const tabs = ['详情', '组别信息', '俱乐部', '赛程', '成绩']
const tabs = ['详情', '赛程', '成绩','俱乐部']
const activeTab = ref(0)

// 判断赛事是否已结束
const isEventEnded = computed(() => {
  if (!eventDetail.value.base) return false
  
  // 主要使用deadline字段判断是否截止
  const deadline = eventDetail.value.base.deadline
  if (deadline) {
    const deadlineTime = new Date(deadline * 1000) // 假设deadline是时间戳
    const currentTime = new Date()
    return currentTime > deadlineTime
  }
  
  return false
})

// 判断是否可以报名
const canRegister = computed(() => {
  return !isEventEnded.value
})

const switchAthlete = () => {
  uni.showToast({
    title: '切换运动员',
    icon: 'none'
  })
}

onLoad((options)=>{
})
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
<style>
.uv-form-item__body__left__content__required {
  color: red;
  /* 改变星号颜色 */
  margin-right: 10rpx !important;
  /* 添加右边距 */
  left: -12px !important;
}
</style>
